package com.ruoyi.common.utils;

import com.ruoyi.common.config.RuoYiConfig;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通知工具类
 *
 * @author javid
 */
public class NoticeUtils {

    @Autowired
    private RuoYiConfig ruoYiConfig;

    public void dingdingNotice(String title, String text, List<String> mobileList) {
        try {
            String body = "";
            String timestamp = String.valueOf(System.currentTimeMillis());
            String sign = dingHmacSHA256(timestamp, ruoYiConfig.getDingdingSecret());
            // 钉钉机器人地址（配置机器人的webhook）
            String dingUrl = "https://oapi.dingtalk.com/robot/send?access_token=" + ruoYiConfig.getDingdingAccessToken() + "&timestamp=" + timestamp + "&sign=" + sign;
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            //组装请求内容
            Map<String, Object> dingdingReq = buildDingdingReq(title, text, false, mobileList);
            HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(dingdingReq, headers);
            ResponseEntity<String> entity = restTemplate.postForEntity(dingUrl, httpEntity, String.class);
            body = entity.getBody();
            System.out.println(body);
        } catch (RestClientException e) {
            System.out.printf("发送钉钉提醒失败：%s", e);
        }
    }

    // 字符串格式的内容
    private static Map<String, Object> buildDingdingReq(String content, boolean isAtAll, List<String> mobileList) {
        //消息内容
        Map<String, String> contentMap = new HashMap<String, String>();
        contentMap.put("content", content);

        //通知人
        Map<String, Object> atMap = new HashMap<String, Object>();
        //1.是否通知所有人
        atMap.put("isAtAll", isAtAll);
        //2.通知具体人的手机号码列表
        atMap.put("atMobiles", mobileList);

        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("msgtype", "text");
        reqMap.put("text", contentMap);
        reqMap.put("at", atMap);

        return reqMap;
    }

    // markdown格式的内容
    private static Map<String, Object> buildDingdingReq(String title, String text, boolean isAtAll, List<String> mobileList) {
        //消息内容
        Map<String, String> contentMap = new HashMap<String, String>();
        contentMap.put("title", title);
        contentMap.put("text", text);

        //通知人
        Map<String, Object> atMap = new HashMap<String, Object>();
        //1.是否通知所有人
        atMap.put("isAtAll", isAtAll);
        //2.通知具体人的手机号码列表
        atMap.put("atMobiles", mobileList);

        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("msgtype", "markdown");
        reqMap.put("markdown", contentMap);
        reqMap.put("at", atMap);

        return reqMap;
    }

    public static String dingHmacSHA256(String timestamp, String secret) {
        try {
            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            return sign;
        } catch (Exception e) {
            System.out.printf("dingHmacSHA256加密失败: %s", e);
        }
        return null;
    }
}
